package com.gxks.lhs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxks.lhs.entity.AddressBook;
import com.gxks.lhs.mapper.AddressBookMapper;
import com.gxks.lhs.service.IAddressBookService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 地址管理 服务实现类
 * </p>
 *
 * @author LuoHaisong
 * @since 2023-05-18
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Override
    public Boolean addAddress(AddressBook addressBook) {
        return save(addressBook);
    }

    @Override
    public Boolean deleteAddress(String userId, Integer id) {
        //根据用户id和地址id删除
        QueryWrapper<AddressBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("id", id);
        return remove(queryWrapper);
    }

    @Override
    public Boolean updateAddress(AddressBook addressBook) {
        return updateById(addressBook);
    }


    @Override
    public List<AddressBook> getAddressByUserId(String userId) {
        QueryWrapper<AddressBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return list(queryWrapper);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean defaultAddr(String userId, Long addrId) {
        //清除原来的默认地址
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, userId);
        updateWrapper.eq(AddressBook::getIsDefault, true);
        update(new AddressBook().setIsDefault(false), updateWrapper);
        //设置新的默认地址
        LambdaUpdateWrapper<AddressBook> updateWrapper2 = new LambdaUpdateWrapper<>();
        updateWrapper2.eq(AddressBook::getUserId, userId);
        updateWrapper2.eq(AddressBook::getId, addrId);
        return update(new AddressBook().setIsDefault(true), updateWrapper2);
    }

    @Override
    public AddressBook getAddress(String userId, Integer id) {
        return getOne(new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId, userId).eq(AddressBook::getId, id));
    }

    @Override
    public AddressBook getDefaultAddress(String userId) {
        return getOne(new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, true));
    }


}
